package com.atguigu.distributed.lock.leecode;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) {
//        Semaphore semaphore = new Semaphore(3);//模拟三个停车位
//        for (int i = 1; i <= 6; i++) {
//            new Thread(()->{
//                try {
//                    semaphore.acquire();
//                    System.out.println(Thread.currentThread().getName()+"\t抢到车位");
//                    try{
//                        TimeUnit.SECONDS.sleep(3);
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
//                    System.out.println(Thread.currentThread().getName()+"\t停车三秒后离开车位");
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }finally {
//                    semaphore.release();
//                }
//            },String.valueOf(i)).start();
//        }


        Semaphore semaphore1 = new Semaphore(3);
        for (int i = 1; i <= 5; i++) {
            new Thread(()->{
                try {
                    semaphore1.acquire();
                    System.out.println(Thread.currentThread().getName()+"\t抢到车位");
                    try{
                        TimeUnit.SECONDS.sleep(3);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"\t停车三秒后离开车位");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }finally {
                    semaphore1.release();
                }


            },String.valueOf(i)).start();
        }
    }
}
